/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package company.beans;

import company.abstractClasses.CompanyAbstractEntityList;
import company.globalEvents.PaidCompanyProductEvent;
import entities.CompanyOrder;
import facades.CompanyOrderFacade;
import java.io.Serializable;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.enterprise.event.Observes;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.transaction.Transactional;

/**
 *
 * @author MIsabel
 */
@Named
@SessionScoped
public class NewOrdersCompanyBean extends CompanyAbstractEntityList<CompanyOrder, CompanyOrderFacade> implements Serializable{
    
    @PostConstruct
    @Override
    public void initEntityList(){
        setEntityList(getCompany().getCompanyOrderList());
    }
    
    @Transactional
    public void observeMessageAddedEvent(@Observes final PaidCompanyProductEvent event) {
        if(getCompany().getIdCompany().equals(event.getCompanyOrder().getCompany().getIdCompany())){
            Collections.replaceAll(getCompany().getCompanyOrderList(),event.getCompanyOrder(),event.getCompanyOrder());
            getCompany().setAvailableCredits(getCompany().getAvailableCredits()+event.getCompanyOrder().getCompanyProduct().getCredits());
        }
    }
    
    public void onCreditsBought(){
        FacesContext context = FacesContext.getCurrentInstance();
        Map map = context.getExternalContext().getRequestParameterMap();
        String idCompanyOrderString = (String) map.get("companyOrder");
        Integer idCompanyOrder = null;
        try {
            idCompanyOrder=new Integer(idCompanyOrderString);
        } catch (NumberFormatException e) {
        }
        CompanyOrder companyOrder = null;
        if(idCompanyOrder!=null){
            for(CompanyOrder co: getCompany().getCompanyOrderList()){
                if(co.getIdCompanyOrder().equals(idCompanyOrder)){
                    companyOrder=co;
                    break;
                }
            }
        }
        Locale locale=context.getViewRoot().getLocale();
        ResourceBundle rb = ResourceBundle.getBundle("messages", locale);
        String successMessage=rb.getString("CreditsUpdated");
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, successMessage, successMessage);  
        context.addMessage(null, message); 
        context.renderResponse();
    }
}
